/*
 *
 *  *    Copyright 2020-2021 Luter.me
 *  *
 *  *    Licensed under the Apache License, Version 2.0 (the "License");
 *  *    you may not use this file except in compliance with the License.
 *  *    You may obtain a copy of the License at
 *  *
 *  *      http://www.apache.org/licenses/LICENSE-2.0
 *  *
 *  *    Unless required by applicable law or agreed to in writing, software
 *  *    distributed under the License is distributed on an "AS IS" BASIS,
 *  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  *    See the License for the specific language governing permissions and
 *  *    limitations under the License.
 *
 */

package com.luter.heimdall.samples.solon.controller;

import com.luter.heimdall.core.annotation.RequiresRole;
import com.luter.heimdall.core.authorization.provider.DocumentUsersDataProvider;
import com.luter.heimdall.core.authorization.provider.model.UserDO;
import com.luter.heimdall.core.details.UserDetails;
import com.luter.heimdall.core.exception.HeimdallException;
import com.luter.heimdall.core.manager.AuthorizationManager;
import com.luter.heimdall.core.token.SimpleToken;
import com.luter.heimdall.core.utils.ObjUtil;
import com.luter.heimdall.core.utils.crypto.Md5Util;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.core.handle.Context;

@Controller
public class UserController {

    @Inject
    private AuthorizationManager authorizationManager;

    @Mapping("/test")
    @RequiresRole("role")
    public Object test() {
        return "你好";
    }

    @Mapping("/user/login")
    public String login() {
        final String username = Context.current().param("username");
        final String password = Context.current().param("password");
        final UserDO userDO = DocumentUsersDataProvider.loadUserByUserName(username);
        if (null == userDO) {
            throw new HeimdallException("Wrong user name or password:NonExisted");
        }
        if (!Md5Util.matches(password, userDO.getPassword())) {
            throw new HeimdallException("Wrong user name or password:ERROR_PW");
        }
        return authorizationManager.getAuthenticationManager()
                .login(new UserDetails().setUserId(userDO.getUserId())
                        .setAppId(userDO.getAppId())
                        .setAttributes(ObjUtil.ConvertObjectToMap(userDO, "password")));
    }

    @Mapping("/user/current")
    public SimpleToken current() {
        return authorizationManager.getAuthenticationManager().getCurrentToken(true);
    }

    @Mapping("/user/logout")
    public SimpleToken logout() {
        return authorizationManager.getAuthenticationManager().logout();
    }
}
